<?php
namespace App\Http\Controllers;
use App\Eloquent\Projects;
use App\Eloquent\TradeRecords;
use App\Eloquent\User;
use App\Admin\Eloquent\ProjectsUser;
use App\Admin\Eloquent\GiftReceive;
use App\Eloquent\ProjectTypeTemplates;
use \Illuminate\Http\Request;
use App\Extensions\Pagination\BoosstrapPageProject;
use App\Admin\Eloquent\Code;
use App\Eloquent\ProjectAttr;
use DB;
use Exception;
use Log;
use QueryBalance;
use CreateHostingCollectTrade;

class ProjectController extends Controller
{
  /**
   * 项目列表
   * @return [type] [description]
   */
  public function list(Request $q){
    $search=$q->all();
    $session_search=$q->session()->get('project_search');
    $session_search=$session_search?$session_search:array();
    $find=array_merge($session_search,$search?$search:array());
    $q->session()->put('project_search', $find);
    $find=$q->session()->get('project_search');

    $list=Projects::whereNotIn('status',['none','stop','down'])->where('start_time','<=',date('Y-m-d H:i:s'));
    //收益率
    if(isset($find['profit']) && $find['profit']!='all'){
      $exp=explode("-",$find['profit']);
      if($exp[0]=='min'){
        $list=$list->where('rate_search','<=',$exp[1]);
      }elseif($exp[1]=='max'){
        $list=$list->where('rate_search','>',$exp[0]);
      }else{
        $list=$list->where('rate_search','>',$exp[0])->where('rate_search','<=',$exp[1]);
      }
    }
    //项目期限
    if(isset($find['time']) && $find['time']!='all'){
      $ar='<=';
      $time_number=explode('-',$find['time']);
      $list=$list->where(function($query) use ($ar,$time_number) {
        $query->orWhere(function($query) use ($ar,$time_number){
          $query->where('finance_time_cate','d')->where('finance_time_num','>',$time_number[0]*30);
          if($time_number['1']!='max'){
            $query->where('finance_time_num','<=',$time_number[1]*30);
          }
        });
        $query->orWhere(function($query) use ($ar,$time_number){
          $query->where('finance_time_cate','m')->where('finance_time_num','>',$time_number[0]);
          if($time_number['1']!='max'){
            $query->where('finance_time_num','<=',$time_number[1]);
          }
        });
        $query->orWhere(function($query) use ($ar,$time_number){
          $query->where('finance_time_cate','mm')->where('finance_time_num','>',$time_number[0]);
          if($time_number['1']!='max'){
            $query->where('finance_time_num','<=',$time_number[1]);
          }
        });
      });
    }
    //项目类型
    if(isset($find['type']) && $find['type']!='all'){
      $list=$list->where('project_type_template_id',$find['type']);
    }
    //项目状态
    if(isset($find['status']) && $find['status']!='all'){
      $list=$list->where('status',$find['status']);
    }
    //起投金额
    if(isset($find['money']) && $find['money']!='all'){
      if(is_array($find['money'])){
        if(!empty($find['money'][0])){
          $list=$list->where('finance_rule_money','>=',$find['money'][0]);
        }
        if(!empty($find['money'][1])){
          $list=$list->where('finance_rule_money','<=',$find['money'][1]);
        }
        if(empty($find['money'][1]) && empty($find['money'][0])){
          $find['money']='all';
        }
      }else{
        $exp=explode("-",$find['money']);
        if($exp[0]!='min'){$list=$list->where('finance_rule_money','>=',$exp[0]);}
        if($exp[1]!='max'){$list=$list->where('finance_rule_money','<=',$exp[1]);}
      }
    }
    $list=$list->join('codes','codes.code','=','status')->orderBy('codes.sort','desc');
    $list=$list->orderBy('projects.created_at','desc')->paginate(8);

    $links=(new BoosstrapPageProject($list))->render();
    $types=ProjectTypeTemplates::get();//项目类型
    $status=Code::where('type_id','project_status')->whereIn('code',['rush','full','payment','finish','late','fail'])->orderBy('sort','desc')->get();//项目状态
    //统计

    return view('web.project.list',compact('list','links','types','status','find'));
  }
	/**
	 * 投资项目
	 * @param  [type]  $id [description]
	 * @param  Request $q  [description]
	 * @return [type]      [description]
	 */
  public function investProject($id,Request $q){
    $data=$q->all();
    $project=Projects::getOneProjects($id);
    if(empty($project)){
      return redirect('/')->withErrors('项目不存在');
    }
    $money=$data['money'];
    if(isset($data['gift_money']) && $data['gift_money']>0){
      $money+=$data['gift_money'];
    }
    $money=floor($money);

    $user=User::user();
    //新手标判断
    if($project->new_projects && ProjectsUser::where('user_id',$user->id)->count()>0){
      abort(600,'已投资过项目，无法投资新手标');
    }
    //本人不能投资项目
    if($project->financier_id==$user->id){abort(600,'不能投资自己的项目');}
    //判断项目投资金额上限
    if($money<$project->finance_rule_money && $project->finance_money-$project->financed_money>$project->finance_rule_money){
      abort(600,'投资金额太少'.$data['money'].'+'.$project->finance_rule_money);
    }
    //判断项目是否封包
    if($project->status=='payment' || !empty($project->projects_file)){
      abort(600,'项目已封包');
    }
    //判断已投金额
    $money<=$project->finance_money-$project->financed_money or abort(600,'超出项目可投金额');
    //判断是否为起投金额的倍数
    if($project->finance_rule_fold && $data['money']%$project->finance_rule_money!=0 && $project->finance_money-$project->financed_money>$project->finance_rule_money){abort(600,'应为起投金额的倍数');}
    //判断余额是否可用
    $sina_balance=$user->queryBalance();
    if($data['money']>$sina_balance['available_balance']){
      return redirect('/recharge')->withErrors('余额不足');
    }
    try {
      DB::beginTransaction();
      //创建托管代收交易
      $sn=createSn();
      $remarks='用户投资';
      $sina_data=[
        'out_trade_no'=>$sn,
        'out_trade_code'=>'1001',
        'summary'=>$remarks,
        // 'goods_id'=>$project->id,
        'payer_id'=>$user->identity_id,
        'payer_identity_type'=>'UID',
        'amount'=>$data['money'],
        'pay_method'=>'online_bank^'.$data['money'].'^SINAPAY,DEBIT,C',
        'collect_trade_type'=>'pre_auth',
        'return_url'=>config('sinapay.notify_url').'/oneProjects/'.$project->id,
        'can_repay_on_failed'=>'Y',
      ];
      //新增交易流水记录
      $records=new TradeRecords(['type'=>2,'project_id'=>$project->id,'sn'=>$sn,'pay_user'=>$user->id,'remarks'=>$remarks,
        'receive_user'=>$project->financier_id,'money'=>$data['money'],'created_at'=>date('Y-m-d H:i:s'),
      ]);
      $records->save();
      //使用项目的投资红包
      if(isset($data['gift_money']) && $data['gift_money']>0){
        //判断项目是否允许使用多个红包
        if($project->gift_money_auto==0 && count($data['gift'])>1){abort(600,'不允许使用多个红包');}
        //判断红包是否可用
        $gifts=GiftReceive::where('status',0)->where('user_id',$user->id)->whereIn('id',$data['gift'])->get();
        if($gifts->sum('money')!=$data['gift_money']){abort(600,'红包不可用');}
        //添加流水记录
        foreach ($gifts as $item) {
          $sn=createSn();
          $remarks='使用红包投资项目';
          TradeRecords::insert(['type'=>7,'project_id'=>$project->id,'sn'=>$sn,'pay_user'=>$user->id,
            'receive_user'=>$project->financier_id,'money'=>$item->money,'created_at'=>date('Y-m-d H:i:s'),
            'remarks'=>$remarks,'gift'=>$item->id,'pid'=>$records->id
          ]);
        }
      }
      DB::commit();
      return CreateHostingCollectTrade::send($sina_data);
    } catch (Exception $e) {
      DB::rollback();
      throw $e;
    }
  }
}